package com.banciyuan.bcywebview.utils.encrypt;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * post请求加密工具类.
 *
 * @author hfxt2008
 */
public class Encrypt {

    static {
        System.loadLibrary("random");
    }

    private final static int TYPE_0 = 0;
    private final static int TYPE_1 = 1;

    private native static String getRandomString(int type);

    public static String getEncryptedParams(String origParams) {
        return getEncryptedParams(origParams, TYPE_0);
    }

    public static String getEncryptedParams(String origParams, int type) {
        return getBase64Str(encrypt(origParams, type));
    }

    public static String getBase64Str(byte[] data) {
        return encodeToString(data, 0);
    }

    /**
     * Base64-encode the given data and return a newly allocated String with the
     * result.
     *
     * @param input the data to encode
     * @param flags controls certain features of the encoded output. Passing
     *              {@code DEFAULT} results in output that adheres to RFC 2045.
     */
    private static String encodeToString(byte[] input, int flags) {
        try {
            return new String(it.sauronsoftware.base64.Base64.encode(input,
                    flags), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            // US-ASCII is guaranteed to be available.
            throw new AssertionError(e);
        }
    }

    /**
     * 加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(String content, int type) {
        byte[] encrypted = null;
        String key = getRandomString(type);
        try {
            if (key == null || (type == TYPE_0 && key.length() != 16)) {
                return null;
            }
            byte[] raw = key.getBytes(Charset.defaultCharset());
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");// "算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            encrypted = cipher.doFinal(content.getBytes("utf-8"));
        } catch (Exception e) {
        }
        return encrypted;
    }

    private static byte[] decrypt(String content, int type) {
        byte[] decrypted = null;
        String key = getRandomString(type);
        try {
            if (key == null || (type == TYPE_0 && key.length() != 16)) {
                return null;
            }
            byte[] raw = key.getBytes(Charset.defaultCharset());
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");// "算法/模式/补码方式"
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            decrypted = cipher.doFinal(content.getBytes("utf-8"));
        } catch (Exception e) {
        }
        return decrypted;
    }
}